package com.cskaoyan.wordmemorize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cskaoyan.wordmemorize.common.aspect.operate.OperateLog;
import com.cskaoyan.wordmemorize.common.aspect.operate.OperateLogConstant;
import com.cskaoyan.wordmemorize.converter.AIReadConverter;
import com.cskaoyan.wordmemorize.dao.entity.UserVocAISituationDO;
import com.cskaoyan.wordmemorize.dao.entity.UserVocAISituationOptionDO;
import com.cskaoyan.wordmemorize.dao.mapper.UserVocAISituationMapper;
import com.cskaoyan.wordmemorize.dao.mapper.UserVocAISituationOptionMapper;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.admin.UserVocAISituationDTO;
import com.cskaoyan.wordmemorize.request.PageRequest;
import com.cskaoyan.wordmemorize.request.UserVocAISituationCommand;
import com.cskaoyan.wordmemorize.request.UserVocAISituationOptionCommand;
import com.cskaoyan.wordmemorize.service.AIReadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AIReadServiceImpl implements AIReadService {


    @Autowired
    UserVocAISituationMapper userVocAISituationMapper;

    @Autowired
    UserVocAISituationOptionMapper userVocAISituationOptionMapper;

    @Autowired
    AIReadConverter aiReadConverter;

    @Override
    @OperateLog(dateType = "词汇", operateType = OperateLogConstant.OPERATE_ADD)
    public void addAISituation(UserVocAISituationCommand command) {

        UserVocAISituationDO situationDO = new UserVocAISituationDO();
        situationDO.setName(command.getName());
        situationDO.setStatus(command.getStatus());
        situationDO.setDescription(command.getDescription());

        int effectiveRow = userVocAISituationMapper.insert(situationDO);

        System.out.println("受影响行数：" + effectiveRow);
        if (command.getOptions() != null && !command.getOptions().isEmpty()) {
            for (UserVocAISituationOptionCommand optionCommand : command.getOptions()) {
                UserVocAISituationOptionDO optionDO = new UserVocAISituationOptionDO();
                optionDO.setSituationId(situationDO.getId()); // 使用新生成的情景ID
                optionDO.setName(optionCommand.getName());
                optionDO.setDescription(optionCommand.getDescription());

                int optionRow = userVocAISituationOptionMapper.insert(optionDO);
                System.out.println("选项受影响行数：" + optionRow);
            }
        }
    }

    @Override
    @OperateLog(dateType = "词汇", operateType = OperateLogConstant.OPERATE_UPDATE)
    public void updateAISituation(UserVocAISituationCommand command) {
        LambdaUpdateWrapper<UserVocAISituationDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserVocAISituationDO::getId, command.getId())
                .set(UserVocAISituationDO::getName, command.getName())
                .set(UserVocAISituationDO::getStatus, command.getStatus())
                .set(UserVocAISituationDO::getDescription, command.getDescription());

        userVocAISituationMapper.update(null, updateWrapper);

        if (command.getOptions() != null) {
            LambdaQueryWrapper<UserVocAISituationOptionDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserVocAISituationOptionDO::getSituationId, command.getId());
            List<UserVocAISituationOptionDO> existingOptions = userVocAISituationOptionMapper.selectList(queryWrapper);

            for (UserVocAISituationOptionCommand optionCommand : command.getOptions()) {
                if (optionCommand.getId() == null) {
                    // 新增选项
                    UserVocAISituationOptionDO newOption = new UserVocAISituationOptionDO();
                    newOption.setSituationId(Long.parseLong(command.getId()));
                    newOption.setName(optionCommand.getName());
                    newOption.setDescription(optionCommand.getDescription());
                    userVocAISituationOptionMapper.insert(newOption);
                } else {
                    LambdaUpdateWrapper<UserVocAISituationOptionDO> optionUpdateWrapper = new LambdaUpdateWrapper<>();
                    optionUpdateWrapper.eq(UserVocAISituationOptionDO::getId, optionCommand.getId())
                            .set(UserVocAISituationOptionDO::getName, optionCommand.getName())
                            .set(UserVocAISituationOptionDO::getDescription, optionCommand.getDescription());
                    userVocAISituationOptionMapper.update(null, optionUpdateWrapper);

                    existingOptions.removeIf(opt -> opt.getId().equals(optionCommand.getId()));
                }
            }

            for (UserVocAISituationOptionDO toDelete : existingOptions) {
                userVocAISituationOptionMapper.deleteById(toDelete.getId());
            }
        }

    }

    @Override
    @OperateLog(dateType = "词汇", operateType = OperateLogConstant.OPERATE_SINGLE_DELETE)
    public void deleteAISituation(Long id) {
        int effectiveRow = userVocAISituationMapper.deleteById(id);
        System.out.println("受影响行数: " + effectiveRow);
    }

    @Override
    @OperateLog(dateType = "词汇", operateType = OperateLogConstant.OPERATE_SINGLE_DELETE)
    public void deleteAISituationOption(Long id) {
        int effectiveRow = userVocAISituationOptionMapper.deleteById(id);
        System.out.println("受影响行数: " + effectiveRow);
    }

    @Override
    @OperateLog(dateType = "词汇", operateType = OperateLogConstant.OPERATE_BATCH_DELETE)
    public void batchDeleteAISituationOption(List<Long> ids) {
        int effectiveRow = userVocAISituationMapper.deleteBatchIds(ids);
        System.out.println("受影响行数: " + effectiveRow);
    }

    @Override
    public PageDTO<UserVocAISituationDTO> getAISituationList(PageRequest pageRequest) {

        if(pageRequest.getPageNum() == null){
            List<UserVocAISituationDO> userVocAISituationDOS = userVocAISituationMapper.selectList(null);

            userVocAISituationDOS.forEach(situation -> {
                LambdaQueryWrapper<UserVocAISituationOptionDO> optionWrapper = new LambdaQueryWrapper<>();
                optionWrapper.eq(UserVocAISituationOptionDO::getSituationId, situation.getId());
                List<UserVocAISituationOptionDO> options = userVocAISituationOptionMapper.selectList(optionWrapper);
                situation.setOptions(options);
            });

            return aiReadConverter.toUserVocAISituationPage(userVocAISituationDOS,(long)userVocAISituationDOS.size());
        }

        Page<UserVocAISituationDO> pageParam = new Page<>(pageRequest.getPageNum(), pageRequest.getCount());
        LambdaQueryWrapper<UserVocAISituationDO> userSituationWrapper = new LambdaQueryWrapper<>();
        if(pageRequest.getKeyword() != null){
            userSituationWrapper.like(UserVocAISituationDO::getName, pageRequest.getKeyword());
        }
        Page<UserVocAISituationDO> userSituationPage = userVocAISituationMapper.selectPage(pageParam, userSituationWrapper);

        userSituationPage.getRecords().forEach(situation -> {
            LambdaQueryWrapper<UserVocAISituationOptionDO> optionWrapper = new LambdaQueryWrapper<>();
            optionWrapper.eq(UserVocAISituationOptionDO::getSituationId, situation.getId());
            List<UserVocAISituationOptionDO> options = userVocAISituationOptionMapper.selectList(optionWrapper);
            situation.setOptions(options);
        });

        return aiReadConverter.toUserVocAISituationPage(userSituationPage.getRecords(), userSituationPage.getTotal());
    }
}
